package main

import (
	"fmt"
	"os"
)

func main() {
	maze := readMaze("basic/maze/maze.in")
	maze = [][]int{
		{0, 1, 0, 0, 0},
		{0, 0, 0, 1, 0},
		{0, 1, 0, 1, 0},
		{1, 1, 1, 0, 0},
		{0, 1, 0, 0, 1},
		{0, 1, 0, 0, 0},
	}

	for _, row := range maze {
		for _, val := range row {
			fmt.Printf("%d ", val)
		}
		fmt.Println()
	}
	start := point{0, 0}
	end := point{len(maze) - 1, len(maze[0]) - 1}
	steps := walk(maze, start, end)

	fmt.Println("=======================")
	for _, row := range steps {
		for _, val := range row {
			fmt.Printf("%3d ", val)
		}
		fmt.Println()
	}
}

func walk(maze [][]int, start, end point) [][]int {
	steps := make([][]int, len(maze))
	for i := range steps {
		steps[i] = make([]int, len(maze[i]))
	}
	Q := []point{start}
	//队列为空的时候跳出循环
	for len(Q) > 0 {
		current := Q[0]
		Q = Q[1:]
		if current == end {
			break
		}
		for _, dir := range dirs {
			//实现坐标位移
			next := current.move(dir)
			//maze at next is 0 && steps at next is 0 && next != start
			temp, ok := next.at(maze)
			if !ok || temp == 1 {
				continue
			}

			temp, ok = next.at(steps)
			if !ok || temp != 0 {
				continue
			}

			if next == start {
				continue
			}
			currentStep, _ := current.at(steps)
			steps[next.i][next.j] = currentStep + 1
			Q = append(Q, next)
		}
	}

	return steps
}

// 每个格子能走的方向
var dirs = [4]point{
	{-1, 0},
	{0, -1},
	{1, 0},
	{0, 1},
}

type point struct {
	i, j int
}

func (p point) move(r point) point {
	return point{p.i + r.i, p.j + r.j}
}

func (p point) at(grid [][]int) (int, bool) {
	if p.i < 0 || p.i >= len(grid) {
		return 0, false
	}
	if p.j < 0 || p.j >= len(grid[p.i]) {
		return 0, false
	}
	return grid[p.i][p.j], true
}

func readMaze(filename string) [][]int {
	file, err := os.Open(filename)
	if err != nil {
		panic(err)
	}
	var row, col int
	fmt.Fscanf(file, "%d %d", &row, &col)
	fmt.Println(row, col)
	maze := make([][]int, row)
	for i := range maze {
		maze[i] = make([]int, col)
		for j := range maze[i] {
			fmt.Fscanf(file, "%d", &maze[i][j])
		}
	}
	return maze
}
